package com.itany.nmms.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itany.nmms.constant.DictConstant;
import com.itany.nmms.constant.ResponseCodeConstant;
import com.itany.nmms.entity.ProductType;
import com.itany.nmms.exception.ProductTypeExistException;
import com.itany.nmms.exception.RequestParameterErrorException;
import com.itany.nmms.service.ProductTypeService;
import com.itany.nmms.util.ParameterUtil;
import com.itany.nmms.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/type")
public class ProductTypeController {

    @Autowired
    private ProductTypeService typeService;

    @RequestMapping("/findAll")
    public ModelAndView findAll(String pageNo,String pageSize){
        ModelAndView mav = new ModelAndView();

        // 判断前台是否传递了分页数据,如果没有传递,设置默认值
        if(ParameterUtil.isNull(pageNo)){
            pageNo = DictConstant.PRODUCT_TYPE_DEFAULT_PAGE_NO;
        }
        if(ParameterUtil.isNull(pageSize)){
            pageSize = DictConstant.PRODUCT_TYPE_DEFAULT_PAGE_SIZE;
        }

        // 分页三部曲
        // 1.设置分页信息,第几页,每页多少条数据
        PageHelper.startPage(Integer.parseInt(pageNo),Integer.parseInt(pageSize));
        // 2.获取业务数据
        List<ProductType> types = typeService.findAll();
        // 3.封装分页对象,对业务数据进行自动分页
        PageInfo<ProductType> typePage = new PageInfo<>(types);

        mav.setViewName("backend/productTypeManager");
        mav.addObject("typePage",typePage);
        return mav;
    }

    @ResponseBody
    @RequestMapping("/addType")
    public ResponseResult addType(String name){
        ResponseResult result = new ResponseResult();

        try {
            typeService.addType(name);
            result.setMessage("成功");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);
        } catch (RequestParameterErrorException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_REQUEST_PARAMETER_ERROR);
        } catch (ProductTypeExistException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }

        return result;
    }

}
